﻿using System;
using System.Text;
using System.ServiceModel;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DXTools.UI.Modules.JavaScriptConverter.Model;
using DXTools.Core;
using DXTools.Core.CrmSdk;
using DXTools.UI.Core.ViewModel;
using DXTools.UI.Modules.JavaScriptConverter.ViewModels;
using System.Collections.ObjectModel;

namespace DXTools.UI.Modules.JavaScriptConverter.DataProviders
{
   
    public class CRMDataProvider : IDataProvider
    {
        Uri _server;

        public CRMDataProvider()
        {
            _server = new Uri(DXTools.Core.ClientScript.GetServerUrl());
        }


        public void RetrieveWebResourceList(AsyncCallback asyncCallback)
        {
            try
            {
                DXTools.Core.CrmSdk.IOrganizationService service = DXTools.Core.WCFHelper.GetConnection(_server);
               
                OrganizationRequest request = new OrganizationRequest();

                QueryExpression query = new QueryExpression();
                query.ColumnSet = new ColumnSet();
                query.ColumnSet.Columns = new ObservableCollection<string>(
                    new string[] { "webresourceid","name" });

                query.Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions = {
                        new ConditionExpression
                        {
                            AttributeName = "webresourcetype",
                            Operator = ConditionOperator.Equal,
                            Values = { 3 }
                        }
                        ,
                        new ConditionExpression
                        {
                            AttributeName = "ishidden",
                            Operator = ConditionOperator.Equal,
                            Values = { "false" }
                        }
                    }
                };
                
                query.EntityName = "webresource";

                service.BeginRetrieveMultiple(query, asyncCallback, service);
                              
               

            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
        }


        public void RetrieveWebResource(String WebResourceId, AsyncCallback asyncCallback)
        {
            try
            {
            DXTools.Core.CrmSdk.IOrganizationService service = DXTools.Core.WCFHelper.GetConnection(_server);

            ColumnSet cols = new ColumnSet();
            //cols.AllColumns = true;

            cols.Columns = new ObservableCollection<string>(new string[] { "webresourceid", "name" , "description" , "content", "displayname" });


            service.BeginRetrieve("webresource", new Guid(WebResourceId), cols, asyncCallback, service);

            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Retreive the web resource by name e.g. dxtools_/JSConverter/ConversionList.xml
        /// </summary>
        /// <param name="WebResourceName"></param>
        /// <param name="asyncCallback"></param>
        public void RetrieveWebResourceByName(String WebResourceName, AsyncCallback asyncCallback)
        {
            try
            {
                DXTools.Core.CrmSdk.IOrganizationService service = DXTools.Core.WCFHelper.GetConnection(_server);


                QueryExpression query = new QueryExpression()
                {
                    EntityName = "webresource",
                    ColumnSet = new ColumnSet() { Columns = new ObservableCollection<string>(new string[] { "webresourceid", "name", "description", "content", "displayname" }) },

                };

                query.Criteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions = {
                        new ConditionExpression
                        {
                            AttributeName = "name",
                            Operator = ConditionOperator.Equal,
                            Values = { WebResourceName }
                        }
                    }
                };

                service.BeginRetrieveMultiple(query, asyncCallback, service);

            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
        }


        public void  UpdateWebResource(String WebResourceId, String Content, AsyncCallback asyncCallback)
        {
            try
            {
                DXTools.Core.CrmSdk.IOrganizationService service = DXTools.Core.WCFHelper.GetConnection(_server);

                String data = Convert.ToBase64String(Encoding.UTF8.GetBytes(Content));

                Entity webResource = new Entity() { LogicalName = "webresource" };
                webResource.Id = new Guid(WebResourceId);
                webResource.Attributes = new AttributeCollection();
                webResource.Attributes.Add(new DXTools.Core.CrmSdk.KeyValuePair<string,object>("content", data));

                service.BeginUpdate(webResource, asyncCallback, service);

            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
        }


       public void PublishWebResource(String WebResourceId, AsyncCallback asyncCallback)
       {
           DXTools.Core.CrmSdk.IOrganizationService service = DXTools.Core.WCFHelper.GetConnection(_server);


           OrganizationRequest publishRequest = new OrganizationRequest();
           publishRequest.RequestName = "PublishXml";

           string publishXml = "<importexportxml><webresources><webresource>" + WebResourceId + "</webresource></webresources></importexportxml>";

           publishRequest.Parameters = new ParameterCollection();
           DXTools.Core.CrmSdk.KeyValuePair<string, object> myParam = new DXTools.Core.CrmSdk.KeyValuePair<string, object>();
           myParam.Key = "ParameterXml";
           myParam.Value = publishXml;

           publishRequest.Parameters.Add(myParam);


           service.BeginExecute(publishRequest, asyncCallback, service);

       }
       
    }
}
